import unittest
from RDS4SQLServer.src.sqlserver import SqlserverConnect


class SqlserverTest(unittest.TestCase):
    conn = None
    cursor = None

    @classmethod
    def setUpClass(cls) -> None:
        cls.conn = SqlserverConnect()
        cls.cursor = cls.conn.cursor()
        create_sql = "create table tmp_blogs (id varchar(20), user_id varchar(20), name varchar(20))"
        cls.cursor.execute(create_sql)

    def test_0_insert(self):
        """测试插入数据"""
        print("插入数据")
        insert_sql = "insert into tmp_blogs values('test_id', 'test_user_id', 'test_name')"
        self.cursor.execute(insert_sql)
        self.conn.commit()

        self.cursor.execute("select name from tmp_blogs")
        name = self.cursor.fetchall()[0][0]
        self.assertEqual(name, "test_name")

    def test_1_update(self):
        """测试更新数据"""
        print("更新数据")
        update_sql = "update tmp_blogs set name = 'update_name' where id = 'test_id'"
        self.cursor.execute(update_sql)
        self.conn.commit()

        self.cursor.execute("select name from tmp_blogs")
        name = self.cursor.fetchall()[0][0]
        self.assertEqual(name, "update_name")

    def test_2_delete(self):
        """测试删除数据"""
        print("删除数据")
        delete_sql = "delete from tmp_blogs where id = 'test_id'"
        self.cursor.execute(delete_sql)
        self.conn.commit()

        self.cursor.execute("select name from tmp_blogs")
        name = self.cursor.fetchall()
        self.assertListEqual(name, [])

    @classmethod
    def tearDownClass(cls) -> None:
        drop_sql = "drop table if exists tmp_blogs"
        cls.cursor.execute(drop_sql)
        cls.conn.commit()
        cls.cursor.close()
        cls.conn.close()


if __name__ == '__main__':
    unittest.main()
